<template>
  <div class="cart">
    <div class="cart-content">
      <Bread home="首页" crumbs="购物车" />
      <template v-if="cartData.allList.effectList.length > 0 || cartData.allList.disabledList?.length > 0">
        <template v-for="(value, key) in cartData.allList" :key="key">
          <template v-if="value.length > 0">
            <div v-if="key === 'disabledList'">失效商品</div>
            <table class="tabel">
              <thead class="table_header_title">
                <th style="width: 56px">
                  <el-checkbox v-if="key === 'effectList'" class="checkbox" label="全选" v-model="cartData.checkedAll" @change="checkedAllChange"></el-checkbox>
                </th>
                <th style="width: 250px">商品信息</th>
                <th style="width: 140px">属性</th>
                <th style="width: 80px">单价</th>
                <th>数量</th>
                <th style="width: 80px">金额</th>
                <th>操作</th>
              </thead>
              <tbody class="table_tbody">
                <template v-for="cart in value" :key="cart.cartId">
                  <tr>
                    <td colspan="7">
                      <div class="info">
                        <el-checkbox v-if="key === 'effectList'" class="goods-outer-checkbox" v-model="cart.isChecked" @change="(val) => onRowCheckedChange(val, cart)"></el-checkbox>
                        <img class="store-icon" src="@/assets/images/dianpuxiao.png" />
                        <span>供应商 : {{ cart.supplierName }}</span>
                      </div>
                    </td>
                  </tr>

                  <tr :class="`${key === 'disabledList' ? 'goods_disabled' : ''} goods`" v-for="goods in cart.cartItemList" :key="goods.goodsId">
                    <td>
                      <el-checkbox v-if="key === 'effectList'" class="goods-inner-checkbox" v-model="goods.isChecked" @change="(val) => onRowCheckedChange(val, cart, goods)"></el-checkbox>
                      <span v-else class="_disabled">失效</span>
                    </td>
                    <td>
                      <div class="goods-info">
                        <img :src="goods.goodsImg" />
                        <span class="goods-name"> {{ goods.goodsName }}</span>
                      </div>
                    </td>
                    <td>
                      <span>{{ goods.goodsSpec }}</span>
                    </td>
                    <td class="goods-currentPrice">
                      <span>¥{{ goods.currentPrice.toFixed(2) }}</span>
                    </td>
                    <td class="goods-num">
                      <el-input-number v-if="key === 'effectList'" v-model="goods.amount" :min="1"
                                       @change="onAmountChange(goods)"></el-input-number>
                      <span v-else>{{ goods.amount }}</span>
                    </td>
                    <td class="goods-totalPrice">
                      <span>¥{{ (goods.currentPrice * (goods.amount || 1)).toFixed(2) }}</span>
                    </td>
                    <td class="last">
                      <Link :underline="true" label="删除" @click="onDelClick(goods, goods.cartItemId)" />
                    </td>
                  </tr>
                </template>

                <tr>
                  <td colspan="7">
                    <div v-if="cartData.list?.length === 0">
                      <el-empty description="暂无商品"></el-empty>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </template>
        </template>
        <div class="footer">
          <div class="footer-content">
            <div class="_left">
              <el-checkbox v-if="cartData.allList.effectList.length > 0" class="btn" label="全选" v-model="cartData.checkedAll" @change="checkedAllChange"></el-checkbox>
              <Link v-if="cartData.allList.effectList.length > 0" :underline="true" label="删除" class="btn" @click="onAllDeleteClick"> </Link>
              <Link v-if="cartData.allList.disabledList.length > 0" :underline="true" class="btn" label="清空失效商品" @click="onDisableClick"> </Link>
            </div>
            <div class="_right" v-if="cartData.allList.effectList.length > 0">
              <span
                >已选商品 <span class="_mount">{{ totals.count }}</span> 件</span
              >
              <div class="_right_btn">
                <span
                  >合计：<span class="_mount">￥ {{ totals.totalPrice.toFixed(2) }} </span></span
                >
                <Button label="结算" class="_button" :class="{ disabled: totals.count === 0 }" @click="onAccountClick" :disabled="totals.count === 0" />
              </div>
            </div>
          </div>
        </div>
      </template>
      <div v-else><el-empty description="购物车空空如也"></el-empty></div>
    </div>
  </div>
</template>
<script setup>
import { reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { cartStore } from '@/store/cart'
import Bread from '@/components/bread/index.vue'
import Link from '@/components/button/link.vue'
import Button from '@/components/button/button.vue'

const _cartStore = cartStore()
const router = useRouter()

const cartData = reactive({
  list: [],
  effectList: [],
  disabledList: [],

  allList: {
    effectList: [],
    disabledList: []
  },
  checkedAll: false
})

const clientheight = document.documentElement.clientHeight - 120 + 'px' || document.body.clientHeight - 120 + 'px'

const totals = computed(() => {
  return cartData.allList.effectList?.reduce(
    (a, b) => {
      const checkItems = b.cartItemList.filter((e) => e.isChecked === true)
      let count = (a.count += checkItems.length)
      let totalPrice = (a.totalPrice += checkItems.reduce((d, e) => d + e.currentPrice * e.amount, 0))
      return { count, totalPrice }
    },
    { count: 0, totalPrice: 0 }
  )
})

const updateChecked = async (checked, cartItemIds) => {
  if (cartItemIds.length === 0) return
  let { err } = await api.post(`/medinstrument/site/cart/updateChecked?cartItemIds=${cartItemIds.join(',')}&checked=${checked ? 'YES' : 'NO'}`)
  if (err) {
    ElMessage.error(err)
  }
}

const delMultipleGoods = async (cartItemIds) => {
  let { err } = await api.post(`/medinstrument/site/cart/batchDelCart?cartItemIds=${cartItemIds}`)
  if (err) {
    ElMessage.error(err)
  } else {
    _cartStore.delAll()
    loadData()
  }
}

const delGood = async (row, cartItemId) => {
  let { err } = await api.post(`/medinstrument/site/cart/delCart?cartItemId=${cartItemId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    _cartStore.delete(row.goodsId)
    loadData()
  }
}

const loadData = async () => {
  let { data, err } = await api.get('/medinstrument/site/cart')
  if (err) {
    ElMessage.error(err)
  } else {
    cartData.list = data.list
    cartData.allList.effectList = []
    cartData.allList.disabledList = []

    data.list.forEach((e) => {
      let effectList = e.cartItemList.filter((item) => item.goodsStatus === 'PUTON')
      if (effectList.length > 0) {
        let effect = { ...e, cartItemList: effectList.map((a) => ({ ...a, isChecked: a.checked === 'YES' })) }
        cartData.allList.effectList.push(effect)
      }
      let disableGoodsList = e.cartItemList.filter((item) => item.goodsStatus === 'PUTOFF')
      if (disableGoodsList.length > 0) {
        let disabled = { ...e, cartItemList: disableGoodsList }
        cartData.allList.disabledList.push(disabled)
      }
    })

    cartData.allList.effectList.forEach((e) => (e.isChecked = e.cartItemList.findIndex((e) => !e.isChecked) === -1))

    cartData.checkedAll = cartData.allList.effectList.findIndex((e) => !e.isChecked) === -1
  }
}

const checkedAllChange = (checked) => {
  const cartItemIds = []
  cartData.allList.effectList.forEach((item) => {
    item.isChecked = checked
    item.cartItemList.forEach((e) => {
      e.isChecked = checked
      cartItemIds.push(e.cartItemId)
    })
  })

  updateChecked(checked, cartItemIds)
}

const onRowCheckedChange = (checked, cart, goods) => {
  const cartItemIds = []

  if (goods) {
    cartItemIds.push(goods.cartItemId)
    cart.isChecked = cart.cartItemList.findIndex((e) => !e.isChecked) === -1
  } else {
    cart.cartItemList.forEach((e) => {
      e.isChecked = checked
      cartItemIds.push(e.cartItemId)
    })
  }

  cartData.checkedAll = cartData.allList.effectList.findIndex((e) => !e.isChecked) === -1
  updateChecked(checked, cartItemIds)
}

const onAmountChange = async (row) => {
  let { err } = await api.post(`/medinstrument/site/cart/updateAmount?amount=${row.amount || 1}&cartItemId=${row.cartItemId}`)
  if (err) {
    ElMessage.error(err)
  }
}

const onDelClick = (row, cartItemId) => {
  ElMessageBox.confirm('确定要删除商品，不可恢复？', '系统', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    cancelButtonClass: 'cancelButtonClass',
    confirmButtonClass: 'confirmButtonClass',
    type: 'warning'
  })
    .then(() => {
      delGood(row, cartItemId)
    })
    .catch(() => {})
}

const onAllDeleteClick = () => {
  const cartItemIds = cartData.allList.effectList.flatMap((e) => e.cartItemList.map((item) => item.cartItemId))

  ElMessageBox.confirm('确定要删除全部商品，不可恢复？', '系统', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    cancelButtonClass: 'cancelButtonClass',
    confirmButtonClass: 'confirmButtonClass',
    type: 'warning'
  })
    .then(() => {
      delMultipleGoods(cartItemIds)
    })
    .catch(() => {})
}

const onDisableClick = () => {
  const cartItemIds = cartData.allList.disabledList.flatMap((e) => e.cartItemList.map((item) => item.cartItemId))

  ElMessageBox.confirm('确定要清空失效商品，不可恢复？', '系统', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    cancelButtonClass: 'cancelButtonClass',
    confirmButtonClass: 'confirmButtonClass',
    type: 'warning'
  })
    .then(() => {
      delMultipleGoods(cartItemIds)
    })
    .catch(() => {})
}

const onAccountClick = () => {
  router.push('/settlement')
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.cart {
  min-height: calc(100% - 523px);

  .cart-content {
    width: 1080px;
    margin: 0px auto;

    .tabel {
      border-collapse: collapse;
      width: 100%;
      margin-bottom: 20px;

      .table_header_title {
        color: var(--span-color-text);
        background: var(--color-background);
        height: 42px;

        th {
          text-align: center;

          .checkbox {
            margin-left: 10px;
          }
        }

        th.price {
          width: 100px;
        }
      }

      .table_tbody {
        :deep(tr) {
          padding: 12px 0 12px 10px;

          td {
            text-align: center;
          }
        }
        .info {
          display: flex;
          align-items: center;
          line-height: 18px;
          padding: 12px 20px 12px 10px;
          box-sizing: border-box;

          .store-icon {
            margin: 0 12px 0 12px;
          }
        }

        .goods {
          td {
            padding: 12px 0 12px 10px;
            line-height: 18px;
            border-top: 1px solid var(--border-color);
            border-bottom: 1px solid var(--border-color);
          }

          td:first-child {
            border-left: 1px solid var(--border-color);
          }

          td.last {
            border-right: 1px solid var(--border-color);
          }

          .goods-info {
            display: flex;
            align-items: center;

            img {
              width: 72px;
              height: 72px;
            }
          }

          .goods-name {
            width: 250px;
            margin-left: 12px;
          }

          .goods-currentPrice,
          .goods-totalPrice {
            font-weight: 600;
          }

          .goods-totalPrice {
            color: var(--color-primary);
          }

          .goods-num .el-input-number :deep(.el-input--small) {
            width: 200px;
            height: 25px;
          }

          .el-input-number--small {
            width: 80px;
            height: 25px;

            :deep(.el-input-number__decrease),
            :deep(.el-input-number__increase) {
              width: 22px;
              height: 23px;
              box-sizing: border-box;
            }
          }

          .remark {
            text-align: left;
            padding: 12px 0 12px 54px;
            font-size: 12px;
            line-height: 16px;
          }
        }

        .goods_disabled {
          td {
            background-color: #f9f9f9;
            color: #909399;
          }

          ._disabled {
            display: inline-block;
            width: 34px;
            height: 18px;
            line-height: 18px;
            font-size: 12px;
            color: #606266;
            background: #e0e0e0;
            border-radius: 2px;
            text-align: center;
          }
        }
      }
    }

    .footer {
      position: sticky;
      bottom: 0;
      height: 50px;
      box-shadow: 0px -4px 12px 0px rgba(0, 0, 0, 0.04);
      border: 1px solid var(--border-color);
      background: #fff;
      z-index: 2;
      margin-top: 30px;

      .footer-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 1080px;
        height: 100%;
        margin: 0 auto;

        ._left {
          display: flex;
          align-items: center;
          justify-content: space-between;
          line-height: 18px;

          .btn {
            margin: 0 12px 0 10px;
          }
        }
        ._right {
          display: flex;
          justify-content: space-between;
          align-items: center;

          ._mount {
            font-size: 18px;
            color: var(--color-primary);
            line-height: 18px;
            font-weight: 600;
          }

          ._right_btn {
            display: flex;
            align-items: center;
            margin-left: 54px;

            ._mount {
              font-size: 20px;
            }
            ._button {
              margin-left: 12px;
              width: 112px;
              height: 50px;
              background: var(--color-primary);
              color: #fff;
              font-size: 20px;
              font-weight: 500;
              border: none;

              &.disabled {
                background: #ccc;
                cursor: not-allowed;
              }
            }
          }
        }
      }
    }
  }
}
</style>
